from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.core.api import wait, Template, exists, swipe, assert_equal


class AppAutomation:
    def __init__(self, use_airtest_input=True, screenshot_each_action=False):
        self.poco = AndroidUiautomationPoco(use_airtest_input=use_airtest_input,
                                            screenshot_each_action=screenshot_each_action)

    def click(self, element_name=None,**kwargs):
        """封装点击操作"""
        self.poco(element_name,**kwargs).click()

    def set_text(self, element_name, text):
        """封装设置文本操作"""
        self.poco(element_name).set_text(text)

    def get_text(self, element_name):
        """封装获取文本操作"""
        return self.poco(element_name).get_text()

    def assert_equal(self, value1, value2, msg):
        """封装断言操作，增加错误处理"""
        try:
            assert_equal(value1, value2, msg=msg)
        except AssertionError as e:
            print(f"断言失败: {msg} | 错误信息: {e}")
            # 可以选择在此处记录日志或者采取其他后续操作
            return False
        return True

    def wait_for_element(self, template, record_pos=(0.009, 0.799), resolution=(1080, 1920)):
        """封装等待元素的操作"""
        wait(Template(template, record_pos=record_pos, resolution=resolution))

    def swipe_screen(self, template, vector=[0, -1], record_pos=(-0.006, 0.01), resolution=(1080, 1920)):
        """封装滑动操作"""
        swipe(Template(template, record_pos=record_pos, resolution=resolution), vector=vector)

    def handle_advertisement(self):
        """处理广告"""
        if exists(Template(r"tpl1736992607515.png", record_pos=(0.003, -0.075), resolution=(1080, 1920))):
            # 如果广告存在，点击广告关闭
            self.poco("android.widget.FrameLayout").child("android.view.View").child("android.view.View").child(
                "android.widget.ImageView").click()
        else:
            print('不存在广告')


# 使用封装后的类进行操作
if __name__ == "__main__":
    kuke = AppAutomation()

    # 打开应用
    kuke.click("库课网校")

    # 等待元素
    kuke.wait_for_element("tpl1736993968628.png")

    # 处理广告
    kuke.handle_advertisement()

    # 登录操作
    kuke.click("com.kuke:id/tv_login")
    kuke.click("com.kuke:id/tv_title_right")
    kuke.set_text("com.kuke:id/et_password_login_phone", '19233829732')
    kuke.set_text("com.kuke:id/et_password", 'wn123456789')
    kuke.click("com.kuke:id/cb_privacy")
    kuke.click("com.kuke:id/tv_password_login")
    kuke.click(text="我的")
    # 断言用户名
    name = kuke.get_text("com.kuke:id/tv_nick_name")
    kuke.assert_equal(name, "测试", msg="登录后用户名断言是否是测试")

    # 滑动
    kuke.swipe_screen("tpl1736993243803.png")

    # 点击账号设置
    kuke.click(text="账号设置")

    # 退出登录操作
    kuke.click("退出登录")
    kuke.click("退出")

    # 断言用户名为“登录/注册”
    name = kuke.get_text("com.kuke:id/tv_nick_name")
    kuke.assert_equal(name, "登录/注册", msg="断言是否成功退出登录")